package cn.ecpay.unionpay.settle.controller;

import cn.ecpay.unionpay.settle.Common.CommonUtil;
import cn.ecpay.unionpay.settle.Common.RespCode;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import cn.ecpay.unionpay.settle.util.SDKConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 批量查询
 * Created by zhaoyanzeng on 2018/11/6.
 */
@RestController
public class BatchQueryController {

    @RequestMapping(value = "/batchQuery", method = RequestMethod.POST)
    public String batchQuery(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        Map<String, String> contentData = convertContentData(req);

        //对请求参数进行签名并发送http post请求，接收同步应答报文
        //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        Map<String, String> reqData = FsasService.sign(contentData, CommonBase.encoding);
        //交易请求url从配置文件读取对应属性文件fsas_sdk.properties中的 fsassdk.backTransUrl;
        String requestBackUrl = SDKConfig.getConfig().getBackRequestUrl();
        //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;
        //这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过
        Map<String, String> rspData = FsasService.doPost(reqData,requestBackUrl, CommonBase.encoding);

        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if(!rspData.isEmpty()){
            if(FsasService.validate(rspData, CommonBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(RespCode.RESP_SUCCESS.equals(respCode)){
                    //成功
                    //TODO 成功后保存数据库和进一步业务处理
                    System.out.println("save..db");
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                    System.out.println("check...");
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        String reqMessage = CommonBase.genHtmlResult(reqData);
        String rspMessage = CommonBase.genHtmlResult(rspData);
//        resp.getWriter().write("交易状态查询（批量）请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+parseStr);
        return "交易状态查询（批量）请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage;
    }

    /**
     * 批量查询异步通知
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/batchQueryNotify", method = RequestMethod.POST)
    public void batchQueryNotify(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        LogUtil.writeLog("批量查询异步通知开始");

        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = CommonUtil.getAllRequestParamStream(req);
        LogUtil.printRequestLog(reqParam);

        if (!FsasService.validate(reqParam, CommonBase.encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");

        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            String respCode = reqParam.get("respCode");
            if (RespCode.RESP_SUCCESS.equals(respCode)) {
                //TODO 成功
            } else {
                //TODO 失败
            }
            LogUtil.writeLog("respCode=" + respCode);
        }
        LogUtil.writeLog("批量查询异步通知结束");
    }


    /**
     * 请求数据整理
     */
    private Map<String, String> convertContentData(HttpServletRequest req) {
        String acqInsCode = req.getParameter("acqInsCode");
        String txnNo = req.getParameter("txnNo");
        String txnDate = req.getParameter("txnDate");
        String batchNo = req.getParameter("batchNo");
        String origTxnDate = req.getParameter("origTxnDate");


        Map<String, String> contentData = new HashMap<>();

        contentData.put("version", CommonBase.version);                  //版本号
        contentData.put("encoding", CommonBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "22");                                   //交易类型 22-交易状态查询（批量）
        contentData.put("sndTime", CommonBase.getSendTime());      //发送时间 格式HHmmss

        contentData.put("acqInsCode", acqInsCode);                        //机构代码
        contentData.put("txnNo", txnNo);                                    //交易流水号
        contentData.put("txnDate",txnDate);                               //交易日期
        contentData.put("batchNo", batchNo);                                    //批次号（原批次号）
        contentData.put("origTxnDate", origTxnDate);                                    //原交易日期
        contentData.put("backUrl", CommonBase.backUrl);
        return contentData;
    }
}
